<?php

namespace App\Util;


use App\Exceptions\ApiException;
use App\Models\WechatSessionsModel;
use App\Services\Admin\AdminMenuService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class LoginUtil
{

    const MENU_KEY = 'admin_menu_key';

    /**
     * 获取登录用户信息
     * @param string $field
     * @return null|string|Model
     */
    public static function getUserInfo($field = '', $guards = null)
    {
        $user = auth($guards)->user();
        return empty($field) ? $user : data_get($user, $field);
    }


    /** 管理员当前数据所属组织
     * @param null $guards
     * @return Model|string|null
     */
    public static function getGroupId($guards = null)
    {
        $group_id = self::getUserInfo('group_id');
        $is_open = self::getUserInfo('is_open');
        if(!$is_open){
            $temp_group_id = self::getUserInfo('temp_group_id');            //如果有这个值认为是切换过组织
            $group_id = $temp_group_id ?: $group_id;
        }

        return $group_id ?? 0;

    }


    /** 查看管理员是否超级权限
     * @param null $guards
     * @return Model|string|null
     */
    public static function checkIsOpen($guards = null)
    {
      return self::getUserInfo('is_open');


    }



    /**
     *  退出登录销毁session喝用户数据
     */
    public static function logout($guards = null)
    {
        $guards = $guards ?? config("auth.defaults.guard");
        $user_id = static::getUserId();
        if ($guards == 'admin') {
            self::clearMenu($user_id);
        }


        auth($guards)->logout();

    }

    /**
     * 获取登录用户user_id (默认主键)
     * @return null|string
     */
    public static function getUserId($guards = null)
    {
        return intval(auth($guards)->id());
    }

    /**
     * 获取登录用户user_id (默认主键)
     * @return null|string
     */
    public static function getChatUserId($guards = "chat")
    {
        return intval(auth($guards)->id());
    }


    protected static function getMenu()
    {
        $user_id = static::getAdminId();

        $key = self::MENU_KEY. $user_id;
        $menu = cache()->get($key);
        return $menu;
    }

    protected static function setMenu($user_id, $menu)
    {

        $key = self::MENU_KEY . $user_id;
        cache()->set($key, $menu, 7200);
    }

    /**　清除菜单缓存 **/
    public static function clearMenu($user_id)
    {

        $key = self::MENU_KEY. $user_id;
        cache()->forget($key);
    }

    /**
     * 验证逻辑权限   --- 当前power是否存在用户menu中
     * @param array $power 权限数据
     * @return bool
     */
    public static function power($power)
    {

        $menu = static::getPower();
        $result = false;
        if (empty($menu)) {
            return $result;
        }
        $menu = array_reduce($menu, 'array_merge', array());

        if (is_array($power)) {
            $power = array_map('strtolower', $power);
            $result = !empty(array_intersect($power, $menu));
        } else {
            $result = in_array(strtolower($power), $menu);
        }

        return $result;
    }

    /**
     * 检查后台用户权限
     * @param array $allowAction //无需检查列表
     * @return bool
     */
    public static function checkPower($allowAction = [])
    {
        $user = static::getUserInfo();
        if (empty($user)) {
            return false;
        }

        //不开权限则无需校验权限
        if (data_get($user, 'is_open') == 0) {
            return true;
        }
        $action = Str::snake(defined('ACTION_NAME') ? ACTION_NAME : '');
        $controller = Str::snake(defined('CONTROLLER_NAME') ? CONTROLLER_NAME : '');
//        $module = Str::snake(defined('MODULE_NAME') ? MODULE_NAME : '');

        $class = defined('NAMESPACE_NAME') ? NAMESPACE_NAME : '';
        $class = explode('/', $class);
        $class = array_map('lcfirst', $class);
        $class = array_map([Str::class, 'snake'], $class);
        $module = implode('\\', $class);                //todo...现在数据库的module使用的是反斜杠 \

        //是否无需检查的函数
        if (!empty($allowAction) && ($allowAction == '*' || in_array($action, array_map_recursive('strtolower', $allowAction)))) {
            return true;
        }
        $power = array(
            join('-', array($module, $controller, $action)),
            join('-', array($module, $controller, '*'))
        );

        //检查权限
        return LoginUtil::power($power);
    }


    /** 获取后台用户权限列表 [menu_id, role_id, user_id] */
    public static function getPower($guards = null)
    {
        $menu = static::getMenu();        //TODO...关闭权限缓存
        if (!empty($menu) && config("start_menu_cache")) {
            return $menu;
        }
        $user_id = self::getAdminId();
        //获取用户权限菜单
        /** @var  AdminMenuService $app */
        $app = app(AdminMenuService::class);
        $menu = $app->getUserPowerMenu();
        //缓存
        self::setMenu($user_id, $menu);
        return $menu;
    }

    /** 对应后台管理员ID */
    public static function getAdminId()
    {
        $guards = $guards ?? config("auth.defaults.guard");

        if ($guards != 'admin') {
            return 0;
        }
        //TODO...获取用户对应的admin_id
        return self::getUserId();       //后期多端需要修改

    }


    /** 对应后台管理员 */
    public static function getAdminMaster()
    {
        $guards = $guards ?? config("auth.defaults.guard");

        if ($guards == 'api') {

        }

        $id = in_array($guards,['master','admin','chat']) ? self::getUserId() : 0;
        return ['type'=>$guards,'id'=>$id];       //后期多端需要修改

    }


    /** 获取用户登录类 */
    public static function getUserClass()
    {
        if (auth()->check()) {
            return auth()->user()::class;
        }
        return null;
    }

}
